layui.config({
    base: "/layui/"
}).extend({
    index: 'lib/index'
}).use(['index', 'form', 'jquery', 'table', 'upload'], function () {
    var form = layui.form,
        table = layui.table,
        upload = layui.upload,
        admin = layui.admin;

    /**
     * 防重复设置
     * @type {boolean}
     */
    var edit_flag = true;

    table.render({
        elem: '#enterprise_Store_table'
        , url: '/enterprise_store/queryData'
        , method: "post"
        , height: 500
        , limit: 50							//显示数目
        , limits: [50, 100]
        , cols: [[
            {field: 'id', width: 100, title: 'id', "align": "center"}
            , {field: 'oemId', title: 'oemId', "align": "center", hide: true}
            , {field: 'userId', title: 'userId', "align": "center", hide: true}
            , {field: 'enterpriseId', title: '资料Id', "align": "center", hide: true}
            , {field: 'name', width: 270, title: '门店名', "align": "center"}
            , {
                field: 'di', width: 180, title: '地区', "align": "center", templet: function (d) {
                    if (d.province != null) {
                        return d.province + d.city + d.district;
                    } else {
                        return "";
                    }
                }
            }
            , {field: 'province', width: 130, title: '省', "align": "center", hide: true}
            , {field: 'city', width: 130, title: '市', "align": "center", hide: true}
            , {field: 'district', width: 130, title: '区', "align": "center", hide: true}
            , {field: 'address', width: 200, title: '详细地址', "align": "center"}
            , {field: 'telephone', width: 130, title: '门店电话', "align": "center"}
            , {field: 'offsetType', width: 180, title: '坐标类型', "align": "center", hide: true}
            , {field: 'longitude', width: 180, title: '经度', "align": "center", hide: true}
            , {field: 'latitude', width: 180, title: '纬度', "align": "center", hide: true}
            , {field: 'type', width: 140, title: '门店等级', "align": "center", hide: true}
            , {field: 'storeMaterialInfo', width: 140, title: '门店图片', "align": "center", hide: true}
            , {field: 'OPT', width: 200, title: '操作', "align": "center", toolbar: "#OptData"}
        ]]
        , request: {
            pageName: 'pageNo' //页码的参数名称，默认：page
            , limitName: 'pageSize' //每页数据量的参数名，默认：limit
        },
        where: {
            type: 1,
        }
        , id: 'enterprise_Store_table'
        , page: true
    });

    table.on('tool(enterprise_Store_table)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var data = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的DOM对象
        if (layEvent === 'store_info') {
            $(".uploadImgPreView").remove();
            if(data.storeMaterialInfo != null){
                for (var i = 0; i <data.storeMaterialInfo.length; i++) {
                    var str = "";
                    str = '<img src="' + data.storeMaterialInfo[i].url + '" height="92px" width="92px" class="layui-upload-img uploadImgPreView">';
                    $('#preview').append(str);
                }
            }
            form.val('add_store_form', {
                "id": data.id,
                "name": data.name,
                "province": data.province,
                "city": data.city,
                "district": data.district,
                "address": data.address,
                "telephone": data.telephone,
                "longitude": data.longitude,
                "latitude": data.latitude,
                "url": data.url
            });
            pca.init('select[name=province]', 'select[name=city]', 'select[name=district]', data.province, data.city, data.district);
            $("#province").find("option:selected").text(data.province);
            $("#city").find("option:selected").text(data.city);
            $("#district").find("option:selected").text(data.district);
            addressChecking();//进行定位
            admin.popup({
                title: '门店详细信息'
                , shade: 0
                , anim: -1
                , offset: "20px"
                , area: ['80%', '700px']
                , skin: 'layui-anim layui-anim-upbit'
                , content: $("#add_store_win")
                , end: function () {
                    table.reload('enterprise_Store_table', {
                        page: {
                            curr: 1 //重新从第 1 页开始
                        }
                        , where: {}
                    });
                }
            });
        }
        ;
    });

    /**
     * 保存门店信息
     */
    form.on('submit(addStoreOk)', function (data) {
        if (edit_flag) {
            var latitude = $("#latitude").val();  //纬度
            var longitude = $("#longitude").val(); //经度
            if (latitude == '' && longitude == '') {
                layer.msg("请先定位!", {
                    offset: '32%'
                    , icon: 5
                    , time: 3000
                });
                return false;
            }
            ;
            edit_flag = false;
            $.ajax({
                url: "/enterprise_store/addStoreDetailedInfo",
                data: data.field,
                type: "post",
                success: function (result) {
                    if (result.code == 1) {
                        edit_flag = true;
                        layer.msg("编辑成功", {
                            offset: '32%'
                            , icon: 1
                            , time: 0
                            , btn: '知道了'
                            , btnAlign: "c"
                            , shade: 0.4
                            , yes: function () {
                                table.reload('enterprise_Store_table', {});
                                layer.closeAll();
                            }
                        })
                    } else {
                        edit_flag = true;
                        layer.msg(result.message, {
                            offset: '32%'
                            , icon: 2
                            , time: 3000
                        }, function () {
                            layer.closeAll();
                        })
                    }
                }
            });
        } else {
            layer.msg("不能重复提交表单", {
                offset: '32%'
                , icon: 2
                , time: 3000
            }, function () {

            })
        }
        return false;
    });

    $(".search_btn").click(function () {
        table.reload('enterprise_Store_table', {
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , where: {
                name: $(".queryTable input[name='name']").val()
            }
        });
    });

    var geocoder, map, marker = null;
    geocoder = new qq.maps.Geocoder();

    function codeAddress() {
        var province = $("#province").val();
        var city = $("#city").val();
        var district = $("#district").val();
        var address = $("#address").val();

        var add = province + "," + city + "," + district + "," + address;
        //对指定地址进行解析
        geocoder.getLocation(add);
        //设置服务请求成功的回调函数
        geocoder.setComplete(function (result) {
            var lat = result.detail.location.lat;
            var lng = result.detail.location.lng;
            $("#latitude").val(lat);  //纬度
            $("#longitude").val(lng); //经度
            // 标志位置
            var center = new qq.maps.LatLng(lat, lng);
            var map = new qq.maps.Map(document.getElementById('container'), {
                center: center,
                zoom: 13
            });
            //创建标记
            var marker = new qq.maps.Marker({
                position: center,
                map: map
            });
        });
        //若服务请求失败，则运行以下函数
        geocoder.setError(function () {
            layer.msg("出错了，请输入正确的地址！！！", {
                offset: '32%'
                , icon: 2
                , time: 3000
            }, function () {

            })
        });
    };


    $("#button").click(function () {
        codeAddress();
    });

    function addressChecking() {
        var latitude = $("#latitude").val();  //纬度
        var longitude = $("#longitude").val(); //经度
        if ((latitude != null && latitude.length > 0) && (longitude != null && longitude.length > 0)) {
            codeAddress();
        }
    }


    /**
     * 清空预览的图片及其对应的成功失败数
     * 原因：如果已经存在预览的图片的话，再次点击上选择图片时，预览图片会不断累加
     * 表面上做上传成功的个数清0，实际后台已经上传成功保存了的，只是没有使用，以最终商品添加的提交的为准
      */
    var success=0;
    var fail=0;
    var imgurls="";

    $("#cleanImgs").click(function () {
        success = 0;
        fail = 0;

        var storeId = $('#id').val();
        $.ajax({
            url: '/enterprise_store/deleteStoreMaterialInfo',
            type: 'post',
            data: {'storeId': storeId},
            success: function (suc) {
                if (suc.code == 1) {
                    layer.msg(suc.message, {icon: 1});
                    $('#preview').html("");
                    $('#url').val("");
                    $(".uploadImgPreView").remove();
                } else {
                    layer.msg(suc.message, {icon: 5});
                }
            }
        });
    });

    upload.render({
        elem: '#select',
        url: '/enterprise_store/upload',
        multiple: true,
        auto: false,
//			上传的单个图片大小
        size: 2048,
//			最多上传的数量
        number: 5,
//			MultipartFile file 对应，layui默认就是file,要改动则相应改动
        field: 'file',
        bindAction: '#start',
        before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#preview').append('<img src="' + result
                    + '" alt="' + file.name
                    + '"height="92px" width="92px" class="layui-upload-img uploadImgPreView">');
            });
            var storeId = $("#id").val();
            this.data.storeId = storeId;
            success = 0;
            fail = 0;
        },
        done: function (res, index, upload) {
            //每个图片上传结束的回调，成功的话，就把新图片的名字保存起来，作为数据提交
            if (res.code != 1) {
                fail++;
            } else {
                success++;
                imgurls = imgurls + "" + res.message + ",";
                console.log(imgurls);
                $('#url').val(imgurls);
            }
        },
        allDone: function (obj) {
            layer.msg("总共要上传图片总数为：" + (fail + success) + "\n"
                + "其中上传成功图片数为：" + success + "\n"
                + "其中上传失败图片数为：" + fail
            )
        }
    });

});

